package com.tssf.car_manage.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class PowerFilter implements Filter {

    // 需要超级管理员权限的操作路径（排除/list）
    private static final String[] SUPER_ADMIN_OPERATION_PATHS = {
            "/admin/add",
            "/admin/edit",
            "/admin/delete",
            "/admin/update"
    };

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession();

        String requestURI = httpRequest.getRequestURI();

        // 检查是否访问需要超级管理员权限的操作路径
        boolean requireSuperAdmin = false;
        for (String path : SUPER_ADMIN_OPERATION_PATHS) {
            if (requestURI.startsWith(path)) {
                requireSuperAdmin = true;
                break;
            }
        }

        if (requireSuperAdmin) {
            // 获取用户角色
            Integer role = (Integer) session.getAttribute("loginRole");

            // 只有role=2的超级管理员可以操作
            if (role == null || role != 2) {
                handleUnauthorized(httpRequest, httpResponse);
                return;
            }
        }

        chain.doFilter(request, response);
    }

    private void handleUnauthorized(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(
                "<script>alert('权限不足，只有超级管理员可以执行此操作！');" +
                        "window.location.href='" + request.getContextPath() + "/admin/list';</script>");
    }


}


